<template>
  <div class="newflows">
    <div class="info">
      <template v-for="(item, index) in treeData">
        <Tree :key="index" :tree="item" :index="index"></Tree>
      </template>
    </div>
    <!-- 审批节点 -->
    <newApprovalModule :elementData="elementData" :approvalVisible="approvalVisible" :approvalEditData="approvalEditData" @sendNodeData='sendNodeData' @closeVisible="closeApproveVisible" />
    <!--抄送人 approval-->
    <copyPeople :copyVisible="copyVisible" :copyEditData="copyEditData" @closeVisible="closeCopy" @sendCopyData="sendCopyData" />
    <!--子流程subprocesses-->
    <subProcesses :childVisible="subprocesses" :childEditData="childEditData" @closeVisible="closeChildren" @sendChildData="sendChildData" />
    <!--设置条件setConditions-->
    <setConditions :tableData="elementData" :conditionData="conditionData" :conditions="conditions" :conditionTable="conditionTable" :conditionVisible="conditionVisible" @sendCondition="sendCondition" @closeVisible="closeVisible" />
  </div>
</template>

<script>
import { getStartEnd, getNodeData, getFormData } from '@/api/Signed/flows'
import bus from './bus';
import Tree from './newflowtree';
import newApprovalModule from './approval/newApprovalModule.vue';
import copyPeople from './approval/copyPeople.vue';
import subProcesses from './approval/subProcesses.vue';
import setConditions from './approval/setConditions.vue';
import { getNodeId } from '@/utils/utils';

export default {
  props: ['processManagerId', 'elementData'],
  components: {
    Tree,
    newApprovalModule,
    copyPeople,
    subProcesses,
    setConditions
  },
  data() {
    return {
      /*审批节点*/
      approvalVisible: false,
      approvalEditData: '', // 审批节点的数据
      childEditData: '', // 子节点的数据
      conditionTable: '', // 条件节点的数据
      copyEditData: '',
      /*抄送人*/
      copyVisible: false,
      /*子流程*/
      subprocesses: false,
      /*设置条件*/
      conditionVisible: false,
      isEdit: false,
      /**
       * @Description: 流程节点树
       * @Param: stepType 1:开始节点； 2: 结束节点；3：审批节点；4：抄送节点；5：条件分支；6：子流程
       * @Author: wangwangwang
       */
      treeData: [],
      /**
       * @Description: 已配置的表单
       * @Param: 
       * @Author: wangwangwang
       */
      tableData: [],
      /*index当前索引
       *key新节点类型
       * data当前数组
       * newdata要添加的数据
       * state状态
       */
      index: null,
      status: null,
      key: null,
      data: "",
      newdata: "",
      conditionData: {},
      conditions: [],
      queryData: {},
      editNodeId: '',
    };
  },
  methods: {
    /**
     * @Description: 初始化数据判断页面是编辑还是新增,同时调接口获取到表单数据将表单数据作为条件
     * @Param: 
     * @Author: wangwangwang
     */
    initData() {
      const params = {
        processManagerId: this.processManagerId,
      }
      getNodeData(params).then(res => { // 获取流程设计原始数据用于回显
        if (res.code === 1001) {
          if (res.data) { // 如果存在数据那么就是编辑
            this.treeData = JSON.parse(res.data.processData);
            console.log(this.treeData)
          } else { // 不存在则为新增
            this.initStarEndNode();
          }
        }
      })
      /**
       * @Description: 自定义表单设置条件
       * @Param: 
       * @Author: wangwangwang
       */
      getFormData({ processManagerId: this.processManagerId }).then(res => {
        if (res.code === 1001) {
          if (res.data) {
            this.tableData = JSON.parse(res.data.formColumnData);
          }
        }
      })
    },
    deleteNode(data, treeData, parentDatas, lastIndex) {
      for (let i in treeData) {
        if (data.nodeId == treeData[i].nodeId) {
          /**
           * @Description: 删除条件节点
           * @Param: 
           * @Author: wangwangwang
           */
          if (data.stepType === 5) {
            if (treeData.length === 2) { // 如果只有2个条件将要进行特殊处理
              let otherData = []
              if (i === '0') {
                otherData = treeData[1]
              } else {
                otherData = treeData[0]
              }
              if (otherData.childNode.length) { // 如果另一个条件上存在数据则将其拼接
                parentDatas.splice(lastIndex, 1);
                let index = lastIndex;
                for (let j in otherData.childNode) {
                  parentDatas.splice(index, 0, otherData.childNode[j]);
                  index++
                }
              } else { // 如果没有数据则删除整个节点
                parentDatas.splice(lastIndex, 1);
              }
            } else {
              treeData.splice(i, 1);
            }
          } else {
            treeData.splice(i, 1);
          }
        } else {
          this.deleteNode(data, treeData[i].childNode, treeData, i);
        }
      }
    },
    /**
     * @Description: 新增节点
     * @Param: 
     * @Author: wangwangwang
     */
    treeDataRecursion(key, data, newdata, treeData) {
      for (let i in treeData) {
        if (data.nodeId == treeData[i].nodeId) {
          switch (key) {
            case 5: {
              let params = {
                nodeId: getNodeId(),
                stepType: key,
                childNode: [
                  {
                    nodeId: getNodeId(),
                    stepType: key,
                    title: "请设置条件",
                    priorityNo: 1,
                    childNode: []
                  },
                  {
                    nodeId: getNodeId(),
                    stepType: key,
                    title: "请设置条件",
                    priorityNo: 2,
                    childNode: []
                  }
                ]
              };
              if (treeData[i].stepType == 1 || treeData[i].stepType == 3) {
                treeData.splice(this.index + 1, 0, params);
              } else {
                if (this.status == 0) {
                  treeData.splice(this.index + 1, 0, params);
                } else {
                  treeData[i].childNode.unshift(params);
                }
              }
              return;
            }
            default: {
              let params = {
                title: key === 3 ? "审批人" : key === 4 ? '抄送人' : '子流程',
                content: "所有人",
                stepType: key,
                data: newdata,
                nodeId: getNodeId()
              };
              if (treeData[i].stepType == 1 || treeData[i].stepType == 3) {
                treeData.splice(this.index + 1, 0, params);
              } else {
                if (this.status == 0) {
                  treeData.splice(this.index + 1, 0, params);
                } else {
                  treeData[i].childNode.unshift(params);
                }
              }
              break;
            }
          }
        } else {
          this.treeDataRecursion(key, data, newdata, treeData[i].childNode);
        }
      }
    },
    /**
     * @Description: 编辑节点
     * @Param: 
     * @Author: wangwangwang
     */
    editNodeData(_, newData) {
      this.setNode(newData, this.treeData);
    },
    setNode (newData, treeData) {
      for (let i = 0; i < treeData.length; i+=1) {
        if (treeData[i].nodeId === this.editNodeId) {
          treeData[i].data = newData;
        }
        if (treeData[i]?.childNode?.length) {
          return this.setNode(newData, treeData[i].childNode)
        }
      }
    },
    /**
     * @Description: 关闭弹层
     * @Param: 
     * @Author: wangwangwang
     */
    closeVisible() {
      this.conditionVisible = false;
    },
    closeApproveVisible() {
      this.approvalVisible = false;
    },
    closeChildren() {
      this.subprocesses = false;
    },
    closeCopy() {
      this.copyVisible = false;
    },
    /**
     * @Description: 获取到设置的节点信息
     * @Param: 
     * @Author: wangwangwang
     */
    sendNodeData(data) {
      this.approvalVisible = false;
      if (this.isEdit) {
        this.editNodeData(this.data, data, this.treeData);
      } else {
        this.treeDataRecursion(this.key, this.data, data, this.treeData);
      }
    },
    /**
     * @Description: 设置条件
     * @Param: 
     * @Author: wangwangwang
     */
    sendCondition(data, priorityNo) {
      this.conditionVisible = false;
      this.setCondition(this.conditionData, data, this.treeData, priorityNo);
    },
    sendChildData(data) {
      this.subprocesses = false;
      if (this.isEdit) {
        this.editNodeData(this.data, data, this.treeData);
      } else {
        this.treeDataRecursion(this.key, this.data, data, this.treeData);
      }
    },
    /**
     * @Description: 获取到将要抄送的人
     * @Param: 
     * @Author: wangwangwang
     */
    sendCopyData(data) {
      this.copyVisible = false;
      if (this.isEdit) {
        this.editNodeData(this.data, data, this.treeData);
      } else {
        this.treeDataRecursion(this.key, this.data, data, this.treeData);
      }
    },
    setCondition(setConditionData, newData, treeData, priorityNo) {
      for (let i in treeData) {
        if (setConditionData.nodeId === treeData[i].nodeId) {
          const oldPriorityNo = treeData[i].priorityNo;
          treeData[i].data = newData;
          treeData[i].priorityNo = priorityNo;
          treeData[i].title = '已设置条件';
          for (let j in treeData) {
            if (treeData[j].priorityNo === priorityNo && setConditionData.nodeId !== treeData[j].nodeId) {
              treeData[j].priorityNo = oldPriorityNo;
            }
          }
          return
        } else {
          this.setCondition(setConditionData, newData, treeData[i].childNode, priorityNo);
        }
      }
    },
    /**
     * @Description: 初始化获取开始和结束节点
     * @Param: 
     * @Author: wangwangwang
     */
    initStarEndNode() {
      this.queryData = this.$route.query;
      const params = {
        processManagerId: this.queryData.id,
        processVersionId: '',
      }
      getStartEnd(params).then(res => {
        if (res.code === 1001) {
          const newData = [];
          const data1 = {
            nodeId: res.data[0].id,
            title: "发起人",
            content: "所有人",
            stepType: 1,
          }
          const data2 = {
            nodeId: res.data[1].id,
            title: "发起人",
            content: "所有人",
            stepType: 2,
          }
          newData.push(data1);
          newData.push(data2);
          this.treeData = newData;
        }
      });
    }
  },
  beforeCreate() {
    this.$store.dispatch("ChangenodeId", 3);
  },
  mounted() {
    bus.$on("addNode", (key, index, data, status) => {
      this.key = key;
      this.data = data;
      this.status = status;
      this.index = index;
      this.isEdit = false;
      switch (key) {
        case 3: {
          this.approvalEditData = '';
          this.approvalVisible = true;
          return;
        }
        case 4: {
          this.copyVisible = true;
          return;
        }
        case 5: {
          this.conditionTable = this.elementData;
          this.treeDataRecursion(key, data, "", this.treeData);
          return;
        }
        case 6: { // 添加子流程
          this.childEditData = '';
          this.subprocesses = true;
          return;
        }
        default: {
          break;
        }
      }
    });
    bus.$on("deleteNode", data => {
      this.deleteNode(data, this.treeData);
    });
    /**
     * @Description: 配置条件
     * @Param: 
     * @Author: wangwangwang
     */
    bus.$on("setConditionEvent", (data, parentData) => {
      this.conditionData = data;
      this.conditionTable = data.data || ''; // 设置要展示的条件
      this.conditions = parentData.length;
      this.conditionVisible = true;
      this.isEdit = true;
    });
    /**
     * @Description: 编辑节点
     * @Param: 
     * @Author: wangwangwang
     */
    bus.$on("editNode", (editData) => {
      this.isEdit = true;
      this.editNodeId = editData.nodeId;
      const { stepType } = editData;
      switch (stepType) {
        case 3: { // 审批节点
          this.approvalVisible = true;
          this.approvalEditData = editData.data;
          return;
        }
        case 4: { // 抄送节点
          this.copyVisible = true;
          this.copyEditData = editData.data;
          return;
        }
        case 6: { // 子流程
          this.subprocesses = true;
          this.childEditData = editData.data;
          return;
        }
        default: {
          break;
        }
      }
    });
    this.initData();
  },
  computed: {
    style() {
      return `width:300px`;
    }
  },
  destroyed() {
    bus.$off("addNode");
    bus.$off("deleteNode");
  }
};
</script>
<style lang="scss" src="./newflows.scss" scoped></style>
<style lang="scss" scoped>
/*弹窗*/
.dialoginfo {
  padding: 0;
  border: 1px #e1e5ed solid;
}
.config-container .el-tabs__content {
  height: calc(100% - 70px) !important;
  overflow: hidden;
}
.newflows {
  width: auto;
  min-width: 100%;
  height: 100%;
  padding-top: 66px;
  background-color: #fafcff;
  overflow: auto;
  border: 1px solid rgba(240, 242, 246, 1);
}
.newflows::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}
.newflows::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.newflows::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
.newflows::-webkit-scrollbar-thumb:hover {
  background: $bg_color;
}
.newflows::-webkit-scrollbar-corner {
  background: $bg_color;
}
.info {
  display: inline-block;
  text-align: center;
  min-width: 100%;
}
</style>
